<template>
  <div class="container">
    <div class="employee-detail">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" class="inputW" />
        </el-form-item>
        <!-- 工号设置为禁用 -->
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工号" disabled class="inputW" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile" class="inputW">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" :disabled="id!==-1" class="inputW" />
        </el-form-item>
        <!-- 级联选择器 -->
        <el-form-item label="部门" prop="departmentId">
          <el-cascader
            v-model="form.departmentId"
            class="inputW"
            :props="defaultProps"
            separator="-"
            :options="departmentOptions"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="form.formOfEmployment" placeholder="请选择聘用形式" class="inputW">
            <el-option label="正式" :value="1" />
            <el-option label="🐃🐎" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker
            v-model="form.timeOfEntry"
            class="inputW"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="转正时间" prop="correctionTime">
          <el-date-picker
            v-model="form.correctionTime"
            class="inputW"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="员工头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveOrUpdate">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { addEmployee, getEmployeeDetail, updateEmployee } from '@/api/employee'
import { convert2Tree } from '@/utils'
export default {
  data() {
    return {
      imageUrl: '',
      defaultProps: {
        value: 'id',
        label: 'name',
        emitPath: false, // 是否返回完整的路径
        checkStrictly: true
      },
      id: -1, // id
      form: {
        username: '', // 姓名
        workNumber: '', // 工号
        mobile: '', // 手机
        departmentId: '', // 部门id
        formOfEmployment: '', // 聘用形式
        timeOfEntry: '', // 入职时间
        correctionTime: '', // 转正时间
        staffPhoto: '' // 员工头像
      },
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }, {
          min: 1, max: 4, message: '姓名为1-4位'
        }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
        //   pattern 正则表达式
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }, {
          validator: (rule, value, callback) => {
            if (this.form.timeOfEntry) {
              if (new Date(this.form.timeOfEntry) > new Date(value)) {
                callback(new Error('转正时间不能小于入职时间'))
                return
              }
            }
            callback()
          }
        }]
      },

      departmentOptions: [
        // 添加更多选项
      ],
      formOfEmploymentOptions: [
        { value: 1, label: '正式' },
        { value: 2, label: '非正式' }
        // 添加更多选项
      ]
    }
  },
  created() {
    // 获取员工详情
    // this.getEmployeeDetail()
    // 获取id
    this.id = this.$route.params.id ?? -1
    this.getDepartmentList()
    if (this.id !== -1) {
      this.form.id = this.id
      // 获取员工详情
      this.getEmployeeDetail()
    }
  },
  methods: {
    async getDepartmentList() {
      const res = await getDepartmentList()
      //   this.deptsOriginal = res
      // this.depts = res
      // 将数据转换为树形结构
      this.departmentOptions = convert2Tree(res)
    },
    async addEmployee() {
      // 添加员工
      console.log('添加员工')
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // 添加员工
        try {
          await addEmployee(this.form)
          // 提示添加成功
          this.$message.success('添加员工成功')
          // 跳转到员工列表页面
          this.$router.push('/employee')
        } catch (error) {
          console.log(error)
          this.$message.error('添加员工失败')
        }
      })
    },
    async getEmployeeDetail() {
      const res = await getEmployeeDetail(this.id)
      this.form = res
    },
    saveOrUpdate() {
      // 保存逻辑
    //   console.log('Form data:', this.form)
      if (this.id === -1) {
        // 添加员工
        this.addEmployee()
      } else {
        // 更新员工
        this.updateEmployee()
      }
    },
    async updateEmployee() {
      try {
        await updateEmployee(this.form)
        this.$message.success('更新员工成功')
        // 跳转到员工列表页面
        this.$router.push('/employee')
      } catch (error) {
        this.$message.error('更新员工失败')
      }
    },
    handleChange() {

    },
    handleAvatarChange(event) {
      const file = event.target.files[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (e) => {
          this.form.avatar = e.target.result
        }
        reader.readAsDataURL(file)
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!')
      //   }
      //   if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!')
      //   }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped lang="scss">
.employee-detail {
    background-color: #fff;
    padding: 20px;
    .el-form {
        width: 60%;
        margin-left: 60px;
        .inputW{
            width: 360px;
        }
    }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
